<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          :content="title"
          @back="goback"
        >
        </el-page-header>
        <div v-if="isEdit" class="card-box--downloadbtn">
          <el-button @click="goback">取消</el-button>
          <el-button v-if="!status || status === '0'" @click="handleSubmit(1)"
            >保存</el-button
          >
          <el-button type="primary" @click="handleSubmit(2)">提交</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>出入申报</span>

          <div v-if="showInfo" @click="showInfo = !showInfo" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showInfo = !showInfo" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <el-form
          :model="formData"
          class="content-box"
          :rules="rules"
          ref="formDataRef"
          label-width="160px"
          v-show="showInfo"
          :disabled="!isEdit"
        >
          <template v-if="true">
            <el-form-item label="物资归属申报人" prop="applyUser">
              <el-input
                v-model.trim="formData.applyUser"
                readonly
                class="width-custom240"
              ></el-input>
            </el-form-item>
            <el-form-item label="物资申报单位" prop="company">
              <el-input
                v-model.trim="formData.company"
                readonly
                class="width-custom240"
              ></el-input>
            </el-form-item>
            <el-form-item label="归属项目" prop="project">
              <el-select
                v-model="formData.project"
                value-key="id"
                class="width-custom240"
                filterable
                remote
                :remote-method="onRemote"
                @change="onProjectChange"
              >
                <el-option
                  class="default-option"
                  v-for="item in projectOptions"
                  :label="item.projectName"
                  :key="item.id"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="归属标段" prop="projectSection">
              <el-select
                v-model="formData.projectSection"
                value-key="id"
                class="width-custom240"
              >
                <el-option
                  class="default-option"
                  v-for="item in sectionOptions"
                  :label="item.sectionName"
                  :key="item.id"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出厂类型" prop="accessType">
              <el-radio-group v-model="formData.accessType">
                <el-radio label="EXIT_MATERIAL">物资出厂</el-radio>
                <el-radio label="EXIT_EMPTY">空车出厂</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="建设单位" prop="factory">
              <el-input
                :modelValue="formData.factory.projectFactoryName"
                readonly
                class="width-custom240"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="车牌号"
              :rules="{
                required: true,
                message: '请输入车牌号',
                trigger: 'change'
              }"
              v-for="(item, index) in formData.licensePlates"
              :key="index"
              :prop="'licensePlates.' + index + '.value'"
            >
              <el-input v-model.trim="item.value" class="width-custom240">
                <template #append v-if="isEdit">
                  <div
                    v-if="index + 1 === formData.licensePlates.length"
                    @click="addLicensePlate"
                  >
                    <i class="el-icon-plus"></i>
                  </div>
                  <div v-else @click="removeLicensePlate(item)">
                    <i class="el-icon-minus"></i>
                  </div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="出场时间" prop="entryExitTime">
              <el-date-picker
                v-model="formData.entryExitTime"
                type="date"
                placeholder="请选择日期"
                class="width-custom240"
                value-format="YYYY-MM-DD"
                :disabled-date="isDisabledDate"
                clearable
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-form>
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>出入物资内容</span>

          <div v-if="showSet" @click="showSet = !showSet" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showSet = !showSet" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="showSet" class="content-box">
          <el-button
            v-if="isEdit"
            type="primary"
            @click="addMaterial"
            class="add-btn"
            >物资填报</el-button
          >
          <div class="table-content">
            <el-table
              :data="tableData"
              stripe
              style="width: 100%"
              :header-cell-style="{
                background: '#F7F9FD',
                color: '#000',
                height: '48px',
                borderTop: '1px soild #E4E8F2'
              }"
            >
              <template #empty>
                <el-empty :image-size="150" description="暂无数据"></el-empty>
              </template>
              <el-table-column type="index" label="序号" width="50px">
              </el-table-column>
              <el-table-column prop="materialName" label="物资名称">
              </el-table-column>
              <el-table-column prop="materialNum" label="数量">
              </el-table-column>
              <el-table-column prop="materialSpec" label="规格型号">
              </el-table-column>
              <el-table-column prop="materialImgs" label="物资图片">
                <template #default="{ row }">
                  <div class="img-box">
                    <div
                      class="img-item"
                      v-for="(item, index) in row.materialImgs"
                      :key="index"
                    >
                      <el-image
                        v-if="item.url"
                        :src="item.url"
                        fit="contain"
                        style="width: 40px"
                      ></el-image>
                      <previewImg v-else :files="item" type="epms"></previewImg>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="180"
                v-if="isEdit"
              >
                <template #default="{ row, $index }">
                  <el-button
                    type="text"
                    size="small"
                    @click="editMaterial(row, $index)"
                    >编辑</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    class="btns-danger"
                    @click="removeMaterial(row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-collapse-transition>
    </el-card>
    <el-dialog
      :title="currentMaterial ? '编辑物资' : '物资填报'"
      v-model="showDialog"
      destroy-on-close
      width="520px"
    >
      <div class="dialog-content">
        <el-form
          :model="materialForm"
          class="content-box"
          :rules="materialUrles"
          label-width="100px"
          ref="materialFormRef"
          v-show="showInfo"
        >
          <el-form-item label="物资名称" prop="materialName">
            <el-input
              v-model.trim="materialForm.materialName"
              class="width-custom200"
            ></el-input>
          </el-form-item>
          <el-form-item label="物资数量" prop="materialNum">
            <el-input
              v-model.trim="materialForm.materialNum"
              maxlength="100"
              class="width-custom200"
            ></el-input>
          </el-form-item>
          <el-form-item label="规格型号" prop="materialSpec">
            <el-input
              v-model.trim="materialForm.materialSpec"
              maxlength="100"
              class="width-custom200"
            ></el-input>
          </el-form-item>
          <el-form-item label="物资图片" prop="materialImgs">
            <image-upload
              :files="materialForm.materialImgs"
              @set-file="
                fileList => {
                  handleChange(fileList);
                }
              "
            ></image-upload>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model.trim="materialForm.remark"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="onDialogConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="选择【建设单位经办人】"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        :onlyInset="true"
        @emitAddUser="showNextJump"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { postDictList } from "/@/api/home";
import { storageLocal } from "/@/utils/storage";
import { postUserInfo } from "/@/api/user";
import { projectManageList, getSection } from "/@/api/projects";
import { addAccess, getAccessInfo, editAccess } from "/@/api/vehicle";
import imageUpload from "/@/components/imageUpload/index.vue";
import { ElMessage } from "element-plus";
import { onFilterFileData } from "/@/utils/file";
import previewImg from "/@/components/previewImg/index.vue";
import { ElMessageBox } from "element-plus";
import AddUser from "../../../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";

export default defineComponent({
  components: { previewImg, imageUpload, AddUser },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const materialFormRef = ref<HTMLFormElement | null>(null) as any;
    const showDialog = ref(false);
    const tableData = ref([]);
    let projectArr = [];
    const projectOptions = ref([]);
    const sectionOptions = ref([]);
    const currentMaterial = ref();
    const status = ref();
    const dialogVisibleTransferAdd = ref(false); // 选择人员的弹窗是否显示
    const acceptUsers = ref([]); // 已选择人员
    let submitType = 1;

    let editIndex = 0;
    let userList = ref([]);
    let projectTypeList = ref([]);
    let typeCode = ref("");
    const marterials = ref([
      {
        picList: []
      }
    ]);
    const materialForm = ref({
      materialName: "", // 物资名称
      materialNum: "",
      materialSpec: "", // 物资规格
      materialImgs: [],
      remark: ""
    });

    let isEdit = route.query?.isEdit === "1";
    let vehicleId = route.query.id;
    let title = isEdit
      ? vehicleId
        ? "车辆出入申请编辑"
        : "车辆出入申请填写"
      : "车辆出入申请查看";

    let state = reactive({
      formData: {
        applyUser: "", // 物资归属申报人
        company: "", // 物资申报单位
        project: null, //归属项目
        projectSection: {}, // 归属标段
        factory: {}, // 建设单位
        accessType: "EXIT_MATERIAL", // 出厂类型
        licensePlates: [{ value: "" }], // 车牌号
        entryExitTime: "" // 进出场时间
      },
      showInfo: true,
      showSet: true
    });

    let proStageList = ref([]);

    const rules = {
      project: [{ required: true, message: "请选择归属项目", trigger: "blur" }],
      accessType: [
        { required: true, message: "请选择出厂类型", trigger: "change" }
      ],
      entryExitTime: [
        { required: true, message: "请选择出厂时间", trigger: "change" }
      ]
    };
    const materialUrles = {
      materialName: [
        { required: true, message: "请输入物资名称", trigger: "blur" }
      ],
      materialImgs: [
        { required: true, message: "请上传物资图片", trigger: "change" }
      ]
    };
    // 项目类型
    const initProjectTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_tmp_pro_type" });
        projectTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    initProjectTypeList();

    const goback = () => {
      router.push("/projects/vehicle/access");
    };

    const addLicensePlate = () => {
      state.formData.licensePlates.push({ value: "" });
    };

    const removeLicensePlate = plate => {
      state.formData.licensePlates = state.formData.licensePlates.filter(
        item => item !== plate
      );
    };

    const addMaterial = () => {
      currentMaterial.value = "";
      materialForm.value = {
        materialName: "", // 物资名称
        materialNum: "",
        materialSpec: "", // 物资规格
        materialImgs: [],
        remark: ""
      };
      showDialog.value = true;
    };

    const removeMaterial = row => {
      ElMessageBox.confirm("确定删除该条记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          // handleDelete(row);
          tableData.value = tableData.value.filter(item => item !== row);
        })
        .catch(() => {});
    };

    const editMaterial = (row, index) => {
      editIndex = index;
      currentMaterial.value = { ...row };
      materialForm.value = { ...row };
      showDialog.value = true;
    };

    const isDisabledDate = time => {
      return time.getTime() + 24 * 60 * 60 * 1000 < new Date().getTime();
    };

    const handleChange = fileList => {
      materialForm.value.materialImgs = fileList;
      console.log("materialImgs", materialForm.value.materialImgs);
    };

    const onDialogConfirm = async () => {
      try {
        const isValid = await new Promise(resolve =>
          materialFormRef.value.validate(resolve)
        );
        if (!isValid) return;
        showDialog.value = false;
        console.log("materialForm", materialForm.value);
        if (currentMaterial.value) {
          // const index = tableData.value.findIndex(
          //   item => item === currentMaterial.value
          // );
          if (tableData.value[editIndex]) {
            tableData.value[editIndex] = { ...materialForm.value };
          }
        } else {
          tableData.value.push({ ...materialForm.value });
        }
        materialForm.value = {
          materialName: "", // 物资名称
          materialNum: "",
          materialSpec: "", // 物资规格
          materialImgs: [],
          remark: ""
        };
      } catch (err) {
        console.log(err);
      }
    };

    const onProjectChange = project => {
      getSectionData(project.id);
      state.formData.projectSection = {};
      state.formData.factory = {
        projectFactoryName: project.projectFactoryName,
        projectFactoryCode: project.projectFactoryCode
      };
    };
    const onRemote = query => {
      if (!query) {
        projectOptions.value = [...projectArr];
      } else {
        projectOptions.value = projectArr.filter(item => item.projectName.includes(query));
      }
    }
    const getUserInfo = async () => {
      if (vehicleId) {
        return;
      }
      try {
        const info = storageLocal.getItem("info");
        const params = {
          id: info ? info?.userId : ""
        };
        const { code, data } = await postUserInfo(params);
        if (code === 200) {
          let { name, companyName } = data;
          state.formData.applyUser = name;
          state.formData.company = companyName;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const getProjectData = async (updateTree?: boolean) => {
      console.log(updateTree);
      const { code, data } = await projectManageList({
        pageNum: 1,
        pageSize: 100000
      });
      if (code === 200) {
        console.log("project", data);
        projectArr = data.list;
        projectOptions.value = data.list;
      }
    };

    //获取标段列表
    const getSectionData = async projectId => {
      let obj = {
        projectId: +projectId,
        pageNum: 1,
        pageSize: 50000
      };
      try {
        const { code, data } = await getSection(obj);
        if (code === 200) {
          sectionOptions.value = data.list;
        }
      } catch (err) {
        console.log(err);
      }
    };

    getUserInfo();
    getProjectData();

    // 请求页面数据
    const getData = async () => {
      if (!vehicleId) {
        return;
      }
      try {
        const { code, data } = await getAccessInfo({ id: vehicleId });
        if (code === 200) {
          console.log("-----data", data);
          const {
            createUserName,
            companyName,
            projectId,
            projectName,
            projectSectionId,
            projectSectionName,
            factoryCode,
            factoryName,
            accessType,
            licensePlates,
            entryExitTime,
            materials
          } = data;
          getSectionData(projectId);
          const baseInfo = {
            applyUser: createUserName, // 物资归属申报人
            company: companyName, // 物资申报单位
            project: { id: projectId, projectName: projectName },
            projectSection: {
              id: projectSectionId,
              sectionName: projectSectionName
            },
            factory: {
              projectFactoryCode: factoryCode,
              projectFactoryName: factoryName
            },
            accessType,
            licensePlates: licensePlates.map(item => ({ value: item })),
            entryExitTime
          };
          const materialInfo = materials.map(item => {
            item.materialImgs = item.materialImgs.map(file => {
              delete file.url;
              return file;
            });
            return { ...item };
          });
          state.formData = { ...state.formData, ...baseInfo };
          tableData.value = materialInfo;
          status.value = data.approveStatus;
          console.log("data", data);
          console.log("baseFormData", state.formData);
          console.log("tableData", tableData.value);
        }
      } catch (err) {
        console.log(err);
      }
    };

    vehicleId && getData();

    const showNextJump = params => {
      submit(params);
    };

    const handleSubmit = async (type = 1) => {
      const isValid = await new Promise(resolve =>
        formDataRef.value.validate(resolve)
      );
      if (!isValid) return;
      if (state.formData.accessType === 'EXIT_MATERIAL' && !tableData.value.length) {
        return ElMessage.error("请填写物资信息");
      }
      submitType = type;
      if (type === 1) {
        return submit()
      }
      dialogVisibleTransferAdd.value = true;
    };
    let submiting = false;
    const submit = async (addUserInfo=null) => {
      const formData = state.formData;
      const params = {
        id: vehicleId,
        type: submitType, // 1为草稿，2为提交
        projectId: formData.project.id,
        projectName: formData.project.projectName,
        projectSectionId: formData.projectSection.id,
        projectSectionName: formData.projectSection.sectionName,
        accessType: formData.accessType,
        factoryCode: formData.factory.projectFactoryCode,
        factoryName: formData.factory.projectFactoryName,
        licensePlates: formData.licensePlates.map(item => item.value),
        entryExitTime: formData.entryExitTime,
        // auditUser: 1000, // TODO
        // auditUser: 100000160,
        auditUser: addUserInfo && addUserInfo?.idList[0]?.id,
        materials: tableData.value.map(item => {
          return {
            materialName: item.materialName,
            materialNum: item.materialNum,
            materialSpec: item.materialSpec,
            materialImgs: onFilterFileData(item.materialImgs),
            remark: item.remark
          };
        })
      };
      if (submiting) return;
      submiting = true;
      try {
        let res;
        if (vehicleId) {
          res = await editAccess(params);
        } else {
          res = await addAccess(params);
        }
        const { code, message } = res;
        commonBackFn(code, message);
      } catch (err) {
        NotifMessage.error(err.message);
      } finally {
        submiting = false;
      }
    };

    const commonBackFn = (code: Number, message: String) => {
      if (code === 200) {
        NotifMessage.success(message);
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    return {
      ...toRefs(state),
      isEdit,
      vehicleId,
      title,
      onProjectChange,
      proStageList,
      formDataRef,
      materialFormRef,
      userList,
      projectTypeList,
      rules,
      materialUrles,
      route,
      goback,
      handleSubmit,
      typeCode,
      showDialog,
      tableData,
      marterials,
      materialForm,
      projectOptions,
      sectionOptions,
      isDisabledDate,
      addLicensePlate,
      removeLicensePlate,
      handleChange,
      onDialogConfirm,
      editMaterial,
      addMaterial,
      removeMaterial,
      currentMaterial,
      status,
      dialogVisibleTransferAdd,
      acceptUsers,
      showNextJump,
      onRemote
    };
  }
});
</script>

<style lang="scss" scoped>
.add-btn {
  margin-bottom: 15px;
}
.btns-danger {
  color: #e45d5d !important;
}
.upload-pic {
  width: 80px;
  height: 80px;
  :deep(.el-upload--picture-card) {
    width: 80px;
    height: 80px;
  }
}
.img-box {
  display: flex;
}
.img-item {
  margin-right: 4px;
}
.upload-pic {
  .el-upload-list__item {
    width: 56px;
    height: 56px;

    .el-upload-list__item-actions {
      font-size: 18px;
    }
  }

  .el-upload--picture-card {
    width: 56px;
    height: 56px;
    background: #fdfdff;
    border-radius: 4px;
    border: 1px solid #e4e8f2;

    i {
      height: 100%;
      width: 100%;
      line-height: 100%;
      font-size: 18px;
      color: #8c939d;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #8895b7;
      }
    }
  }
}
.dialog-content {
  padding: 20px;
}
</style>
